/**  
 * All rights Reserved, Designed By www.beonelot.com
 * @Package: com.jinxin.platform.eleinspect.service.impl
 * @Filename: EleinspectMappingPointItemsServiceImpl.java
 * @Description: TODO(EleinspectMappingPointItemsService接口实现)
 * @author: 金鑫智慧
 * @date: 2020-03-30
 * @version: V1.0
 * @Copyright: 2020 www.beonelot.com Inc. All rights reserved.
 * 注意：本内容仅限于重庆金鑫智慧科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
package com.jinxin.platform.cdelecinspect.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.cdelecinspect.constant.Constants;
import com.jinxin.platform.cdelecinspect.domain.SysUserVO;
import com.jinxin.platform.cdelecinspect.mapper.*;
import com.jinxin.platform.cdelecinspect.mapper.pojo.*;
import com.jinxin.platform.cdelecinspect.result.ResultEntity;
import com.jinxin.platform.cdelecinspect.result.ResultTool;
import com.jinxin.platform.cdelecinspect.rpc.SysUserRpc;
import com.jinxin.platform.cdelecinspect.service.EleinspectMappingPointItemsService;
import com.jinxin.platform.cdelecinspect.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * TODO(EleinspectMappingPointItemsService接口实现)
 * @Classn: EleinspectMappingPointItemsServiceImpl
 * @author Lynn
 * @date 2020-03-30
 */
@Slf4j
@Service
public class EleinspectMappingPointItemsServiceImpl implements EleinspectMappingPointItemsService {
    @Autowired
    private EleinspectMappingPointItemsMapper pointItemsMapper;
    @Autowired
    private EleinspectRecordMapper recordMapper;
    @Autowired
    private EleinspectItemRecordMapper itemRecordMapper;
    @Autowired
    private EleinspectAttachmentMapper attachmentMapper;
    @Autowired
    private CdelecinspectStatisticsMapper statisticsMapper;
    @Autowired
    private SysUserRpc sysUserRpc;

    @Override
    public List<EleinspectMappingPointItems> list(HashMap param) {
        return pointItemsMapper.list(param);
    }

    @Override
    public List<EleinspectPointRecords> listPointRecords(HashMap param) {
        return pointItemsMapper.listPointRecords(param);
    }

    @Override
    public int listPointRecordsCount(HashMap param) {
        return pointItemsMapper.listPointRecordsCount(param);
    }

    @Override
    public List<EleinspectMappingPointItems> listPointItems(HashMap param) {
        return pointItemsMapper.listPointItems(param);
    }

    @Override
    public int listPointItemsCount(HashMap param) {
        return 0;
    }

    @Override
    public int deleteByIds(List<String> idList) {
        return pointItemsMapper.deleteByIds(idList);
    }

    @Override
    public int deleteItemsByIds(List<String> idList) {
        return pointItemsMapper.deleteItemsByIds(idList);
    }

    @Override
    public int deletePlItemsByIds(List<String> idList) {
        return pointItemsMapper.deletePlItemsByIds(idList);
    }

    @Override
    public int insert(EleinspectMappingPointItems eleinspectMappingPointItems) {
        return pointItemsMapper.insert(eleinspectMappingPointItems);
    }

    @Override
    public int deleteByPointId(String mappingPointId) {
        return pointItemsMapper.deleteByPointId(mappingPointId);
    }

    @Override
    public int updateByKey(EleinspectMappingPointItems eleinspectMappingPointItems) {
        return pointItemsMapper.updateByKey(eleinspectMappingPointItems);
    }

    @Override
    public int deleteByItemIds(List<String> idList) {
        return pointItemsMapper.deleteByItemIds(idList);
    }

    @Override
    public int deleteByItemId(String itemId,String pointId) {
        return pointItemsMapper.deleteByItemId(itemId,pointId);
    }

    @Override
    @Transactional
    public boolean deleteAll(String params) {
        if (!StringUtils.isEmpty(params)) {
            JSONObject jsonObject = JSONObject.parseObject(params);
            if(jsonObject.containsKey("rIds")){
                String idArr = jsonObject.getString("rIds");
                String pidArr = jsonObject.getString("pIds");
                String midArr = jsonObject.getString("mIds");
                List<String> idList = JSONArray.parseArray(idArr, String.class);
                List<String> pidList = JSONArray.parseArray(pidArr, String.class);
                List<String> midList = JSONArray.parseArray(midArr, String.class);

                if(idList.size() > 0){
                    int num = pointItemsMapper.deleteByIds(idList);
                    if (num > 0){
                        pointItemsMapper.deleteItemsByIds(pidList);
                        //pointItemsMapper.deletePlItemsByIds(midList);
                        return true;
                    }else {
                        log.info("deleteAll fail");
                        return false;
                    }
                }else {
                    log.info("参数错误");
                    return false;
                }
            }
        }
        log.info("参数错误");
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity submitItem(EleinspectMappingPointItems mappingPointItems,String lineId) {
        if(mappingPointItems == null || StringUtils.isEmpty(mappingPointItems.getMappingId())
         || StringUtils.isEmpty(lineId)){
            log.info("submitItem 参数错误");
            return ResultTool.fail("参数错误");
        }
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null){
            log.info("获取当前用户失败: ");
            return ResultTool.fail("获取当前用户失败");
        }
        HashMap param = new HashMap();
        param.put("recordPointId",mappingPointItems.getMappingPointId());
        param.put("recordTaskId",mappingPointItems.getTaskId());
        param.put("recordLineId",lineId);
        param.put("recordInspectId",currentUser.getUserId());
        EleinspectRecord record = recordMapper.selectOne(param);
//        if(record != null){
//            record.setRecordPointStatus(mappingPointItems.getMappingResult());
//            record.setRecordInspectTime(new Date());
//            record.setRecordMissedInspect(0);
//            recordMapper.updateByKey(record);
//        }
//        int count = pointItemsMapper.updateByKey(mappingPointItems);
        if(record != null){
            if(StringUtils.isEmpty(record.getRecordClockinTime())){
                return ResultTool.fail("请先打卡");
            }
            HashMap param2 = new HashMap();
            param2.put("itemPointRecordId", record.getRecordId());
            param2.put("itemRecordItemId", mappingPointItems.getMappingItemsId());
            EleinspectItemRecord itemRecord = itemRecordMapper.selectOne(param2);
            if(!StringUtils.isEmpty(itemRecord.getItemRecordStatus())){
                return ResultTool.ok("该项目记录已提交，请勿再次提交.");
            }
            itemRecord.setItemRecordTime(new Date());
            itemRecord.setItemRecordStatus(mappingPointItems.getMappingResult());
            itemRecord.setRecordDealwith(mappingPointItems.getRecordDealwith());
            String detail = mappingPointItems.getMappingProblemDetail();
            if(!StringUtils.isEmpty(detail)){
                itemRecord.setItemRecordDescription(detail);
            }
            itemRecordMapper.updateByKey(itemRecord);
            String attachments = mappingPointItems.getAttachments();
            if(!StringUtils.isEmpty(attachments)){
                String[] attachs = attachments.split(",");
                for(String path : attachs){
                    EleinspectAttachment attachment = new EleinspectAttachment();
                    attachment.setId(Utils.getUuid());
                    attachment.setMainId(itemRecord.getItemRecordId());
                    attachment.setPath(path);
                    attachmentMapper.insert(attachment);
                }
            }
            return ResultTool.ok("提交成功");
        }
        return ResultTool.fail("提交失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity submitPoint(String pointId, String taskId, String lineId) {
        if(StringUtils.isEmpty(pointId) || StringUtils.isEmpty(taskId)
                || StringUtils.isEmpty(lineId)){
            log.info("submitPoint 参数错误");
            return ResultTool.fail("参数错误");
        }
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null){
            log.info("获取当前用户失败: ");
            return ResultTool.fail("获取当前用户失败");
        }
        HashMap param = new HashMap();
        param.put("recordPointId",pointId);
        param.put("recordTaskId",taskId);
        param.put("recordLineId",lineId);
        param.put("recordInspectId",currentUser.getUserId());
        EleinspectRecord record = recordMapper.selectOne(param);
        if(record != null){
            // 提交过的不用再提交
            if(record.getRecordPointStatus() != null){
                return ResultTool.fail("巡检项已提交，请勿重复提交");
            }
            String recordId = record.getRecordId();
            HashMap param2 = new HashMap();
            param2.put("itemPointRecordId",recordId);
            List<EleinspectItemRecord> list = itemRecordMapper.list(param2);
            boolean isAllPass = true;
            for(EleinspectItemRecord itemRecord : list){
                if(Constants.TASK_ITEM_RESULT_FAIL.equals(itemRecord.getItemRecordStatus())){
                    isAllPass = false;
                }
            }
            int status = isAllPass ? 0 : 1;
            record.setRecordPointStatus(status);
            record.setRecordInspectTime(LocalDateTime.now());
            record.setRecordMissedInspect(0);
            int count = recordMapper.updateByKey(record);
            if(count > 0){
                return ResultTool.ok("提交成功");
            }else {
                return ResultTool.fail("提交失败,请重试");
            }
        }
        return ResultTool.fail("参数错误");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity clockIn(EleinspectRecord record) {
        if(record == null || StringUtils.isEmpty(record.getRecordTaskId())
        || StringUtils.isEmpty(record.getRecordPointId()) || StringUtils.isEmpty(record.getRecordLineId())
        || StringUtils.isEmpty(record.getAttachments())){
            log.info("clockIn 参数错误");
            return ResultTool.fail("参数错误");
        }
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null){
            log.info("获取当前用户失败: ");
            return ResultTool.fail("获取当前用户失败");
        }
        String userId = currentUser.getUserId();
        HashMap param = new HashMap();
        param.put("recordPointId",record.getRecordPointId());
        param.put("recordTaskId",record.getRecordTaskId());
        param.put("recordLineId",record.getRecordLineId());
        param.put("recordInspectId",userId);
        EleinspectRecord item = recordMapper.selectOne(param);
        int count = 0;
        if(item != null){
            // 已打卡
            if(!StringUtils.isEmpty(item.getRecordClockinTime())){
                return ResultTool.fail("已打卡");
            }
            record.setRecordId(item.getRecordId());
            record.setRecordClockinTime(LocalDateTime.now());
            record.setRecordInspectTime(LocalDateTime.now());
            count = recordMapper.updateByKey(record);
            String attachments = record.getAttachments();
            if(!StringUtils.isEmpty(attachments)){
                String[] attachs = attachments.split(",");
                for(String path : attachs){
                    EleinspectAttachment attachment = new EleinspectAttachment();
                    attachment.setId(Utils.getUuid());
                    attachment.setMainId(item.getRecordId());
                    attachment.setPath(path);
                    attachmentMapper.insert(attachment);
                }
            }
        }
        if(count > 0){
            // 更新统计表数据
            log.info("开始更新统计表数据");
            CdelecinspectStatistics statistics = statisticsMapper.getById(userId);
            if(statistics == null){
                statistics = new CdelecinspectStatistics();
                statistics.setId(userId);
                statistics.setStaffId(userId);
                statistics.setStaff(currentUser.getUserName());
                statistics.setFirstInspectTime(new Date());
                statistics.setLatestInspectTime(new Date());
                statisticsMapper.insert(statistics);
                log.info("新增统计表数据成功");
            }
            return ResultTool.ok("打卡成功");
        }
        return ResultTool.fail("打卡失败,请重试");
    }
}
